﻿using System.Threading;

namespace Core.Threading.Counters
{
    public sealed class CountdownLatch
    {
        private readonly object _locker = new object();
        private int _remain;

        public CountdownLatch()
        {
        }

        public CountdownLatch(int initialValue)
        {
            _remain = initialValue;
        }

        public void Increment()
        {
            lock (_locker)
            {
                _remain++;
            }
        }

        public void Decrement()
        {
            lock (_locker)
            {
                _remain--;
                if (_remain == 0)
                    Monitor.PulseAll(_locker);
            }
        }

        public void Wait()
        {
            lock (_locker)
            {
                if (_remain != 0)
                    Monitor.Wait(_locker);
            }
        }
    }
}